package com.cbgolf.oa.activity.publiz;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.cbgolf.oa.R;
import com.cbgolf.oa.activity.BaseNewActivity;
import com.cbgolf.oa.activity.bill.ShoppingActivity;
import com.cbgolf.oa.activity.coupon.CouponActivity;
import com.cbgolf.oa.activity.message.MessageActivity;
import com.cbgolf.oa.activity.message.MessageCenterActivity;
import com.cbgolf.oa.activity.order.OrderActivity;
import com.cbgolf.oa.activity.order.OrderDetailsActivity;
import com.cbgolf.oa.activity.parkdetails.ParkMapActivity;
import com.cbgolf.oa.activity.permission.PermissionCheckActivity;
import com.cbgolf.oa.activity.result.ScoreCardActivity;
import com.cbgolf.oa.activity.statistics.StatisticsActivity;
import com.cbgolf.oa.activity.statistics.TeetimeActivity;
import com.cbgolf.oa.app.AppManager;
import com.cbgolf.oa.contract.IMainContract;
import com.cbgolf.oa.contract.IMainContract.IMainView;
import com.cbgolf.oa.contract.IMainContract.IMainWaiter;
import com.cbgolf.oa.entity.ParkBean;
import com.cbgolf.oa.event.EventMenus;
import com.cbgolf.oa.event.EventPark;
import com.cbgolf.oa.event.Events;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.manager.DialogManager;
import com.cbgolf.oa.manager.DialogManager.IDialogManagerWaiter;
import com.cbgolf.oa.manager.LocationManager.ILocationWaiter;
import com.cbgolf.oa.manager.MenuManager;
import com.cbgolf.oa.manager.OrderManager;
import com.cbgolf.oa.manager.ReceiverManager;
import com.cbgolf.oa.manager.WsStompManager;
import com.cbgolf.oa.manager.WsStompManager.IWsManagerWaiter;
import com.cbgolf.oa.presenter.MainPresenterImp;
import com.cbgolf.oa.service.LocationService;
import com.cbgolf.oa.util.ClassUtil;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.EnumUtil;
import com.cbgolf.oa.util.PermissionUtils;
import com.cbgolf.oa.util.ServiceUtil;
import com.cbgolf.oa.util.StatusBarUtil;
import com.cbgolf.oa.util.UpdateManager;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.viewbean.OrderBean;
import com.cbgolf.oa.views.MainViewImp;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author lq
 * @date 2017/11/3
 */

public class MainActivity extends BaseNewActivity implements IMainWaiter,
    UpdateManager.IVersionWorker, ILocationWaiter, IWsManagerWaiter {

  private IMainView view;
  private IMainContract.IMainPresenter presenter;

  private boolean isOnce = true;
  private boolean isSendSuccess;
  private ParkBean mParkData;

  private Class[] acts = new Class[]{
      StatisticsActivity.class,
      StatisticsActivity.class,
      StatisticsActivity.class,
      StatisticsActivity.class,
      StatisticsActivity.class,
      TeetimeActivity.class,
      //
      PermissionCheckActivity.class,
//      FairwayActivity.class,
      ParkMapActivity.class,
      ScoreCardActivity.class,
      OrderActivity.class,
      //
      ShoppingActivity.class,
      MessageActivity.class,
      CouponActivity.class
  };

  @Override
  protected int getLayoutId() {
    return R.layout.a_main;
  }

  @Override
  protected void init(Bundle savedInstanceState) {
    EventBus.getDefault().register(this);
    view = new MainViewImp(this, this);
    presenter = new MainPresenterImp(view);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
    if (null != locationIntent) {
      stopService(locationIntent);
      locationIntent = null;
    }
    LocationService.stopLocation();
    WsStompManager.getInstance().release();
    ReceiverManager.getInstance().unBindAliAccount();
  }

  @Override
  protected void onResume() {
    super.onResume();
    initLocation();
    AppManager.getNewInstance().finishOthersActivity(this);
    presenter.refreshAll(isOnce);
    checkVersion();
    ReceiverManager.getInstance().bindAliPush();

  }


  @Subscribe(threadMode = ThreadMode.MAIN)
  public void requestOver(EventMenus event) {
    isOnce = false;
    view.requestOver(event);
  }

  @Subscribe(threadMode = ThreadMode.MAIN)
  public void requestOver(EventPark event) {
    if (null == event || event.msgTarget != DataManager.PARK_MAP_LATLON_MAIN) {
      return;
    }
    mParkData = event.parkBean;
    WsStompManager.getInstance().setParkBean(mParkData);
    WsStompManager.getInstance().sendLatLngStomp();

//    WsStompManager.getInstance().setSendWaiter(this);
//    WsStompManager.getInstance().reconnect();
//    WsStompManager.getInstance().sendLatLngStomp();
  }

  private Intent locationIntent;

  private void initLocation() {
    if (!PermissionUtils.hasAllLocationPermission()) {
      DialogManager.getInstance().showRequestPermissionDialog(this,
          PermissionUtils.getLocationPermissionNames(),
          new IDialogManagerWaiter() {
            @Override
            public void doSubmit() {
              requestCode = PermissionUtils.REQUEST_LOCAION_PERMISSIONS;
              requestPermission(PermissionUtils.getLocationNeedPermission());
            }

            @Override
            public void doCancel() {

            }
          });
    } else {
      DialogManager.getInstance().release();
      if (!ServiceUtil.isServiceRunning(context, LocationService.class.getName())) {
        locationIntent = new Intent(this, LocationService.class);
        startService(locationIntent);
      }
      LocationService.setWorker(this);
      if (LocationService.isStoped()) {
        LocationService.startLocation();
      }
    }
  }

  private UpdateManager updateManager;

  //检查是否有新版本
  public void checkVersion() {
    if (null == updateManager) {
      updateManager = new UpdateManager(context, this, 0);
    }
    updateManager.checkUpdate();
  }

  @Override
  protected void setStatusBar() {
    StatusBarUtil.setColorForDrawerLayout(this, findViewById(R.id.drawer_layout),
        getResources().getColor(R.color.transparent), 0);
  }

  @Override
  protected void onKeyBack() {
    back();
  }

  @Override
  public String getActivityTitle() {
    return DataUtil.getCourseName();
  }

  @Override
  public void back() {
    moveTaskToBack(true);
  }


  @Override
  public void quitOA() {
    mStartActivity(LoginActivity.class);
    ClassUtil.finish(this);
  }

  @Override
  public void showOrderDetails(OrderBean bean) {
    ClassUtil.startActivity(context, new Intent(context, OrderDetailsActivity.class)
        .putExtra(DataManager.KEY_ORDER_ID, orderId)
        .putExtra(DataManager.KEY_TYPE, EnumUtil.getOrderType(bean.orderClassification)));
  }

  @Override
  public void reload() {
    presenter.refreshAll(true);
  }

  @Override
  public void onClickModifyPwd() {
    mStartActivity(PwdModifyActivity.class);
  }

  @Override
  public void onClickMenu(int index) {
    if (index <= MenuManager.MENU_PLAYER_STATISTICS) {
      int[] mTypes = new int[]{
          DataManager.STATISTICS_BUSINESS_ALL, DataManager.STATISTICS_BOOK_ALL,
          DataManager.STATISTICS_CADDIE_ALL, DataManager.STATISTICS_BILL_ALL,
          DataManager.STATISTICS_PLAYER_ALL
      };
      ClassUtil.startActivity(context, new Intent(context, acts[index])
          .putExtra(DataManager.KEY_TYPE, mTypes[index]));
      return;
    }
    if (index == MenuManager.MENU_PARK_MAP_STATISTICS) {
      EventBus.getDefault().postSticky(new Events.Builder()
          .parkBean(mParkData)
          .msgTarget(DataManager.MAIN_PARK_DATA)
          .build());
      mStartActivity(acts[index]);
      return;
    }
    mStartActivity(acts[index]);
  }

  @Override
  public void onClickMsg() {
    mStartActivity(MessageCenterActivity.class);
  }

  @Override
  public void onClickQrCode() {
    if (!PermissionUtils.hasAllCameraPermission()) {
      DialogManager.getInstance().showRequestPermissionDialog(this,
          PermissionUtils.getCameraPermissionNames(),
          new IDialogManagerWaiter() {
            @Override
            public void doSubmit() {
              requestCode = PermissionUtils.REQUEST_CAMERA_PERMISSIONS;
              requestPermission(PermissionUtils.getCameraNeedPermission());
            }

            @Override
            public void doCancel() {
            }
          });
    } else {
      DialogManager.getInstance().release();
      /*ZxingConfig是配置类  可以设置是否显示底部布局，闪光灯，相册，是否播放提示音  震动等动能
       * 也可以不传这个参数
       * 不传的话  默认都为默认不震动  其他都为true
       * */
      Intent intent = new Intent(this, CaptureActivity.class);
      ZxingConfig config = new ZxingConfig();
      //底部布局（包括闪光灯和相册）
      config.setShowbottomLayout(false);
      config.setPlayBeep(false);//是否播放提示音
      config.setShake(true);//是否震动
      config.setShowAlbum(true);//是否显示相册
      config.setShowFlashLight(true);//是否显示闪光灯
      intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
      startActivityForResult(intent, PermissionUtils.REQUEST_QR_CODE);
    }
  }


  @Override
  public void requestUpdatePermission() {
    DialogManager.getInstance().showRequestPermissionDialog(this,
        PermissionUtils.getCameraPermissionNames(),
        new IDialogManagerWaiter() {
          @Override
          public void doSubmit() {
            requestCode = PermissionUtils.REQUEST_UPDATE_PERMISSIONS;
            requestPermission(PermissionUtils.getCameraNeedPermission());
          }

          @Override
          public void doCancel() {

          }
        });
  }

  @Override
  public void toSettingGetInstallPermission() {
    requestCode = PermissionUtils.REQUEST_INSTALL_APK_PERMISSION;
    gotoSettingPermission();
  }

  private String orderId;
  private int requestCode;

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PermissionUtils.REQUEST_INSTALL_APK_PERMISSION && null != updateManager) {
      //再次执行安装流程，包含权限判断
      updateManager.installApk();
      return;
    }
    // 扫描二维码/条码回传
    if (requestCode == PermissionUtils.REQUEST_QR_CODE) {
      String content = DataUtil.getStringExtra(data, Constant.CODED_CONTENT);
      Log.e("content-----------", content + "----");
      if (Util.isEquals(DataUtil.getJsonString(content, DataManager.KEY_TYPE),
          OrderManager.ORDER_CONFIRM)) {
        orderId = DataUtil.getJsonString(content, DataManager.KEY_ORDER_ID);
        presenter.confirmOrder(orderId,
            DataUtil.getJsonString(content, DataManager.KEY_ORDER_CODE));
        return;
      }
      return;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      if (DataUtil.arrayIsNull(permissions)) {
        return;
      }
      // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
      if (ContextCompat.checkSelfPermission(this, permissions[0])
          == PackageManager.PERMISSION_GRANTED) {
        DialogManager.getInstance().release();
        switch (requestCode) {
          case PermissionUtils.REQUEST_UPDATE_PERMISSIONS:
            if (null != updateManager) {
              updateManager.showDownloadDialog();
            }
            break;
          case PermissionUtils.REQUEST_LOCAION_PERMISSIONS:
            initLocation();
            break;
          case PermissionUtils.REQUEST_CAMERA_PERMISSIONS:
            onClickQrCode();
            break;
          default:
            break;
        }
      }
    }
  }


  @Override
  public void locationSuccess(AMapLocation location) {
    if (!isSendSuccess ||
        LocationService.isOutDis(LocationService.lastLatlng, LocationService.newLatlng)) {
      WsStompManager.getInstance().sendLatLngStomp();
    }
  }

  @Override
  public void locationFail() {
    LocationService.startLocation();
  }


  @Override
  public void onMessage(String msg) {

  }

  @Override
  public void onSendOver(boolean isSuccess) {
    isSendSuccess = isSuccess;
  }

  @Override
  public void onOutRange() {

  }

  @Override
  protected void getPermissionSuccess() {
    switch (requestCode) {
      case PermissionUtils.REQUEST_LOCAION_PERMISSIONS:
        initLocation();
        break;
      case PermissionUtils.REQUEST_UPDATE_PERMISSIONS:
        if (null != updateManager) {
          updateManager.showDownloadDialog();
        }
        break;
      case PermissionUtils.REQUEST_CAMERA_PERMISSIONS:
        onClickQrCode();
        break;
      default:
        break;
    }
  }

  @Override
  protected void getPermissionFail() {
    super.getPermissionFail();
    gotoSettingPermission();
    switch (requestCode) {
      case PermissionUtils.REQUEST_CAMERA_PERMISSIONS:
        Util.show("没有权限无法扫描");
        break;
      default:
        break;
    }
  }

  private void gotoSettingPermission() {
    try {
      Intent intent;
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        intent = new Intent()
            .setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            .setData(Uri.fromParts("package", getPackageName(), null));
      } else {
        //注意这个是8.0新API
        intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
      }
      startActivityForResult(intent, requestCode);
      overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
    } catch (Exception e) {
    }
  }

}
